package com.xmmj.baselibrary.base.activity.mvvm

import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.xmmj.baselibrary.base.activity.base.BaseActivity
import java.lang.reflect.ParameterizedType

/**
 * 支持MVVM架构的Activity
 */
abstract class BaseMvvmActivity<DB : ViewDataBinding, VM : BaseViewModel<*>> : BaseActivity() {
    lateinit var mDataBinding: DB
    lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        initViewModel()
        initViewDataBinding()
        observeLiveData()
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataBinding.unbind()
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val type = this.javaClass.genericSuperclass
        val modelClass = if (type is ParameterizedType) {
            val modelClassList = type.actualTypeArguments
            if (modelClassList.size > 1) {
                modelClassList[1] as Class<*>
            } else if (modelClassList.size == 1) {
                modelClassList[0] as Class<*>
            } else {
                BaseViewModel::class.java
            }
        } else {
            BaseViewModel::class.java
        }
        //创建ViewModel
        mViewModel = createViewModel<ViewModel>(this, modelClass) as VM
        //添加观察者
        lifecycle.addObserver(mViewModel)
        //注册被观察者
        mViewModel.lifecycleOwner = this
    }

    /**
     * 初始化DataBinding
     */
    private fun initViewDataBinding() {
        mDataBinding = DataBindingUtil.setContentView(this, getContentViewId())
        //注册被观察者
        mDataBinding.lifecycleOwner = this
        //绑定ViewModel
        mDataBinding.setVariable(getVariableId(), mViewModel)
    }

    /**
     * 观察基础UI事件
     */
    private fun observeLiveData() {
        mViewModel.showLoadingLiveData!!.observe(this) { showLoading(it) }
        mViewModel.hideLoadingLiveData!!.observe(this) { hideLoading() }
        mViewModel.toastLiveData!!.observe(this) { toast(it) }
        mViewModel.reLoginLiveData!!.observe(this) { onReLogin() }
        mViewModel.requestLiveData!!.observe(this) { onRequest() }
        mViewModel.finishLiveData!!.observe(this) { finish() }
        mViewModel.finishRefreshLiveData!!.observe(this) { finishRefresh() }
        mViewModel.finishLoadMoreLiveData!!.observe(this) { finishLoadMore(it) }
        mViewModel.setResultLiveData!!.observe(this) { setResult(it.resultCode, it.data) }
        mViewModel.showEmptyLiveData!!.observe(this) {
            showEmpty(it.isShow, it.imageId, it.hintText)
        }
        mViewModel.showErrorLiveData!!.observe(this) {
            showError(it.imageId, it.errorText, it.btnText)
        }
        mViewModel.setFragmentLiveData!!.observe(this) {
            setCurrentFragment(it.id, it.fragment)
        }
        mViewModel.requestPermissionLiveData!!.observe(this) {
            requestPermission(it.permissions, it.successAction, it.successAction, it.description)
        }
    }

    /**
     * 创建ViewModel
     */
    open fun <T : ViewModel> createViewModel(activity: FragmentActivity, cls: Class<*>): T {
        return ViewModelProvider(activity).get(this.toString(), cls as Class<T>)
    }

    /**
     * 获取model变量id
     */
    abstract fun getVariableId(): Int

    /**
     * 获取布局id
     */
    abstract fun getContentViewId(): Int
}